import random
import uuid
from datetime import datetime
from django.db import transaction
from django.db.models import Q
from rest_framework.generics import ListAPIView
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet

from cart.models import Cart
from cart.ser import CartSer
from course.models import Course
from order.models import UserCoupon, Coupons, OrderDetails, Orders
from order.ser import UserCouponSer, CouponSer, OrdersSer, OrderDetailsSer
from user.models import User
from user.ser import UserSer
from utils.alipayUtil import AliPaySDK
# from utils.alipayutil import AliPaySDK
from utils.authentication import MyAuthentication
from utils.myredis import myredis


# Create your views here.
class OrderView(APIView):
    def get(self, request):
        user = request.query_params.get('user')
        cart = Cart.objects.filter(user=user, selected=True)
        ser = CartSer(cart, many=True)
        return Response({'msg': 'OK', 'data': ser.data})


class UserScore(APIView):
    def get(self, request):
        id = request.query_params.get('user')
        user = User.objects.filter(id=id).first()
        ser = UserSer(user)
        return Response(ser.data)


class UserCouponView(APIView):
    authentication_classes = [MyAuthentication]

    def get(self, request):
        id = request.query_params.get('user')
        all = UserCoupon.objects.filter(user=id)
        ser = UserCouponSer(all, many=True)
        return Response({'msg': 'OK', "data": ser.data})


def getCode():
    return datetime.now().strftime("%Y%m%d%H%M%S") + str(random.randint(1000, 9999))


def getuuid():
    return str(uuid.uuid1())


class OrderCreate(APIView):
    # authentication_classes = [MyAuthentication]

    def post(self, request):
        with transaction.atomic():
            sav = transaction.savepoint()
            user = request.data.get('user')
            paytype = request.data.get('paytype')
            str1 = myredis.getstr(user)
            if str1:
                return Response({'msg': '订单已提交，请勿重复提交'})
            else:
                try:
                    orderdata = {
                        'user': user,
                        'paytype': paytype,
                        'ordercode': getCode(),
                        'totalprice': 0,
                        'realprice': 0,
                        'status': 0,
                    }

                    coursedata = Cart.objects.filter(user=user, selected=True)
                    if coursedata:
                        myredis.setstr(user, getuuid())
                        for course in coursedata:
                            orderdata['totalprice'] += course.course.price
                        score = request.data.get('score', None)
                        coupon = request.data.get('coupon', None)
                        users = User.objects.filter(id=user).first()
                        if score is not None:
                            if users.score >= int(score):
                                orderdata['realprice'] = float(orderdata['totalprice']) - int(score) / 10
                                orderdata['score'] = score
                        if coupon is not None:
                            coupondata = Coupons.objects.filter(id=coupon).first()
                            if coupondata.condition < orderdata['totalprice']:
                                orderdata['realprice'] = orderdata['totalprice'] - int(coupondata.price)
                                orderdata['coupon'] = coupon
                        ser = OrdersSer(data=orderdata)
                        if ser.is_valid():
                            ser.save()
                        for course in coursedata:
                            print(course)
                            orderdetail = {
                                'order': ser.data.get('id'),
                                'courseid': course.course.id,
                                'coursename': course.course.name,
                                'courseprice': course.course.price,
                                'cover': course.course.cover,
                                'type': course.course.level
                            }
                            orderdetailser = OrderDetailsSer(data=orderdetail)
                            if orderdetailser.is_valid():
                                orderdetailser.save()
                            else:
                                print(orderdetailser.errors)
                        coursedata.delete()
                        transaction.savepoint_commit(sav)
                        myredis.delstr(user)
                        return Response({'msg': 'OK', 'data': ser.data})
                    else:

                        return Response({'msg': '当前未选择任何商品'})
                except Exception as e:
                    print(e)
                    transaction.savepoint_rollback(sav)
                    return Response({'msg': 'Error'})


class Pagination(PageNumberPagination):
    page_size = 2
    page_query_param = 'page'
    page_size_query_param = 'size'


class OrderList(ListAPIView):
    queryset = Orders.objects.all()
    serializer_class = OrdersSer
    pagination_class = Pagination
    authentication_classes = [MyAuthentication]

    def get_queryset(self):
        query = Q(user=self.request.query_params.get('user'))
        if self.request.query_params.get('status') != '-1':
            query &= Q(status=self.request.query_params.get('status'))

        return self.queryset.filter(query)


class OrderDetailsList(APIView):
    def get(self, request):
        data = OrderDetails.objects.filter(order=request.query_params.get('id'))
        ser = OrderDetailsSer(data, many=True)
        return Response(ser.data)


class AlipayGet(APIView):
    # authentication_classes = [MyAuthentication]
    def get(self, request):
        order = request.query_params.get('order')
        orders = Orders.objects.filter(id=order).first()
        myalipay = AliPaySDK()
        linkstr = myalipay.page_pay(orders.id, orders.realprice, '支付啦!!!!')
        return Response(linkstr)


class EndMeny(APIView):
    def get(self, request):
        data = request.query_params
        ali = AliPaySDK()
        success = ali.check_sign(data.dict())
        if success:
            order = Orders.objects.filter(id=data['out_trade_no']).first()
            if order:
                order.status = 1
                order.paycode = data['trade_no']
                order.paytime = data['timestamp']
                order.save()
                if order.score > 0:
                    user = User.objects.get(id=order.user.id)
                    user.score = user.score - order.score
                    user.save()
                if order.coupon is not None:
                    usercoupon = UserCoupon.objects.filter(id=order.coupon.id)
                    usercoupon.is_del = True
                    usercoupon.save()
            ser = OrdersSer(order)
            return Response({'msg': 'OK', 'data': {
                'course_list':ser.data['orderdetails_set'],
                'pay_time':ser.data['paytime'],
                'real_price':ser.data['realprice'],
            }})
        else:
            return Response("支付失败")
